<template>
  <el-card>
    <!-- 1.0 标题 -->
    <template #header>
      <h2>商品添加</h2>
    </template>
    <!-- 2.0 内容 -->
    <div>
      <!-- 添加数据的表单 -->
      <el-form
        :model="goodsForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="mini"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goodsForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="cate">
          <el-select v-model="goodsForm.cate" placeholder="请选择">
            <el-option
              v-for="item in allc"
              :key="item.cateName"
              :label="item.cateName"
              :value="item.cateName"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="goodsForm.price"
            :min="1"
            :max="100"
            label="描述文字"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:5000/goods/goods_img_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="goodsForm.desc"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { categories, editshop } from '../../api/shop'
export default {
  data() {
    return {
      // 双向数据绑定
      goodsForm: {
        name: '',
        cate: '',
        price: 0,
        desc: ''
      },
      // 规则
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cate: [
          { required: true, message: '请选择分类名称', trigger: 'change' }
        ],
        price: [{ required: true, message: '请确定价格', trigger: 'change' }],
        desc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      imageUrl: '',
      allc: [],
      pin: 'http://127.0.0.1:5000/upload/imgs/goods_img/'
    }
  },
  created() {
    this.allcate()
  },
  methods: {
    // 获得所有的是商品分类
    async allcate() {
      const data = await categories()
      // console.log(data)
      this.allc = data.categories
    },
    // 如果验证成功，就发请求
    submitForm(goodsForm) {
      this.$refs[goodsForm].validate(async valid => {
        if (valid) {
          // 当表单验证通过，则可以发起请求
          if (this.imageUrl) {
            const data = await editshop({
              name: this.goodsForm.name,
              category: this.goodsForm.cate,
              price: this.goodsForm.price,
              goodsDesc: this.goodsForm.desc,
              imgUrl: this.imageUrl
            })
            // console.log(data)
            if (data === 0) {
              this.$message({
                type: 'success',
                message: data.msg
              })
            }
            this.resetForm(goodsForm)
            this.$router.push('/commodity/list')
          } else {
            this.$message.error('请上传图片')
          }
        } else {
          this.$message.error('你咋啥都不填呢！！！')
          return false
        }
      })
    },
    // 清空
    resetForm(goodsForm) {
      this.$refs[goodsForm].resetFields()
    },
    // 图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // console.log(res)
      this.imageUrl = this.pin + res.imgUrl
      // console.log(this.imageUrl)
    },
    // 图片的格式的规则
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // 判断当前图片的type类型是否在上面的数组中
      // arr.includes(file.type)
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 193px;
}
/deep/ .el-textarea {
  width: 193px;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
